# Create server parameters for stdio connection
import asyncio
import os

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_core.prompts import PromptTemplate
from langchain_mcp_adapters.tools import load_mcp_tools

from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain_community.document_loaders import PyPDFLoader
from langchain_core.tools import tool

server_params = StdioServerParameters(
    command="npx",
    args=["-y", "@notionhq/notion-mcp-server"],
    env={
        "OPENAPI_MCP_HEADERS": "{\"Authorization\": \"Bearer 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\", \"Notion-Version\": \"2022-06-28\" }"
    }
)

async def load_resume(file_path):
    loader = PyPDFLoader(file_path)
    pages = []
    async for page in loader.alazy_load():
        pages.append(page.page_content)
    return pages


@tool
def send_sms(message , mobile_number):
    """Dummy function for send short message"""
    print(message)
    return f"Successfully sent message to {mobile_number}"

@tool
def send_email(message: str, recipient: str) -> str:
    """Dummy function for sending an e-mail."""
    print(message)
    return f"Successfully sent email to {recipient}."

class HireAgent:

    def __init__(self):
        self.llm = ChatOpenAI(
            api_key=os.getenv("DASHSCOPE_APIKEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            model="qwen-max",
        )
        self.prompt = PromptTemplate.from_template("""
          我们正在招聘销售岗位，请分析以下简历，并对简历进行评级，简历分为三个等级：优秀，良好，不合适，
          将评级后的简历内容概要通过创建新页面的方式写入notion指定的页面中，要记录应聘者的姓名，联系方式以及评级，
          如果求职者的评级为优秀，请帮我发送一封邀请面试的邮件给他
          该notion页面的页面Id是: 1e0a3f7ee3cf80519bb2d6a7a64e8bb4
          以下是简历内容：
          {docs}
        """)

    async def process(self, file_path):
        docs = await load_resume(file_path)
        print(docs)
        async with stdio_client(server_params) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                tools = await load_mcp_tools(session)
                tools.append(send_email)
                tools.append(send_sms)
                print(tools)
                hire_agent = initialize_agent(
                    tools=tools,
                    llm=self.llm,
                    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
                    verbose=True,
                )
                prompt_input = await self.prompt.ainvoke({"docs": "\n".join(docs)})
                result = await hire_agent.ainvoke(prompt_input)
                print(result)


if __name__ == '__main__':
    agent = HireAgent()
    asyncio.run(agent.process("C:\\Users\\xmin\\Desktop\\xmin.pdf"))
